package cn.gdut.chengcai.admin.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gdut.chengcai.base.CommentUtil;
import cn.gdut.chengcai.base.ConstantUtil;
import cn.gdut.chengcai.base.EmailUtil;
import cn.gdut.chengcai.base.MessageUtil;
import cn.gdut.chengcai.base.Pager;
import cn.gdut.chengcai.base.PagerUtil;
import cn.gdut.chengcai.base.RequestUtil;
import cn.gdut.chengcai.base.ResponseData;
import cn.gdut.chengcai.entity.CommentInfo;
import cn.gdut.chengcai.entity.CommentInfoExample;
import cn.gdut.chengcai.entity.CourseInfo;
import cn.gdut.chengcai.entity.MemberInfo;
import cn.gdut.chengcai.enums.EmailTemplateType;
import cn.gdut.chengcai.service.CommentInfoService;
import cn.gdut.chengcai.service.CourseInfoService;
import cn.gdut.chengcai.service.EmailLogInfoService;
import cn.gdut.chengcai.service.EmailTemplateInfoService;
import cn.gdut.chengcai.service.KeyValueInfoService;
import cn.gdut.chengcai.service.MemberInfoService;
import cn.gdut.chengcai.vo.CommentInfoVo;

@Controller
@RequestMapping("/admin/comment")
public class Admin_CommentController {

	@Autowired
	protected CommentInfoService commentInfoService;

	@Autowired
	protected CourseInfoService courseInfoService;

	@Autowired
	protected MemberInfoService memberInfoService;

	@Autowired
	protected EmailLogInfoService emailLogInfoService;

	@Autowired
	protected EmailTemplateInfoService emailTemplateInfoService;

	@Autowired
	protected KeyValueInfoService keyValueInfoService;

	@RequestMapping("/list")
	public String list(HttpSession session, ModelMap map) {

		CommentInfoExample example = new CommentInfoExample();
		example.createCriteria().andIsDeletedEqualTo(false);
		List<CommentInfo> listTotal = commentInfoService.selectByExample(example);
		Long itemCount = Long.valueOf(String.valueOf(listTotal.size()));
		Pager pager = PagerUtil.getPager(session, itemCount);
		int fromIndex = (pager.getPageNo() - 1) * pager.getPageSize();
		if (fromIndex >= listTotal.size()) {
			fromIndex = 0;
			pager.setPageNo(1);
			session.setAttribute(ConstantUtil.STR_PAGE_NO, "1");
		}
		int toIndex = fromIndex + pager.getPageSize();
		if (toIndex >= listTotal.size()) {
			toIndex = listTotal.size();
		}
		List<CommentInfo> list = listTotal.subList(fromIndex, toIndex);
		if ((null != list) && (list.size() > 0)) {

			try {
				List<CommentInfoVo> voList = new ArrayList<>();
				CommentUtil.fillVoList(list, voList);
				map.put("list", voList);
				session.setAttribute("pager", pager);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return "/admin/comment/list";
	}

	/**
	 * 评论的删除操作
	 */
	@RequestMapping(value = "/delete/{id}", method = { RequestMethod.POST })
	@ResponseBody
	public ResponseData<Object> commentDeleteAction(@PathVariable Long id) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {
			// 逻辑删除
			CommentInfo comment = commentInfoService.selectByPrimaryKey(id);
			comment.setIsDeleted(true);
			commentInfoService.updateByPrimaryKey(comment);

			// 更新课程评论信息
			CourseInfo courseInfo = courseInfoService.selectByPrimaryKey(comment.getTargetId());
			courseInfo.setCommentCount(courseInfo.getCommentCount() - 1);
			courseInfoService.updateByPrimaryKey(courseInfo);
			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 评论的处理操作
	 */
	@RequestMapping(value = "/handle/{id}", method = { RequestMethod.POST })
	@ResponseBody
	public ResponseData<Object> commentHandleAction(HttpServletRequest request, @PathVariable Long id) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {

			CommentInfo commentInfo = commentInfoService.selectByPrimaryKey(id);
			MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(commentInfo.getMemberId());
			String ip = RequestUtil.getRemoteHost(request);
			String[] args = new String[1];
			args[0] = memberInfo.getEmail();

			// 发送警告邮件（邮件模板）

			if (EmailUtil.sendSystemMail(emailLogInfoService, emailTemplateInfoService, keyValueInfoService, ip,
					EmailTemplateType.WARNING.getValue(), memberInfo.getEmail(), args) == false) {
				result.setMessage(MessageUtil.EMAIL_SEND_FAILURE);
				return result;
			}

			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 评论的详情页
	 */
	@RequestMapping("/detail/{id}")
	public String commentDetail(ModelMap map, @PathVariable Long id) {
		CommentInfo entity = commentInfoService.selectByPrimaryKey(id);
		CommentInfoVo vo = new CommentInfoVo();
		try {
			CommentUtil.fillVo(entity, vo);
			map.put("entity", vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/admin/comment/detail";

	}
}